package com.telecom.at.front;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.json.JSONObject;

import com.telecom.at.db.dac.Dac;
import com.telecom.at.db.model.Doc;
import com.telecom.at.db.model.User;

@WebServlet("/front/UploadDoc")
@MultipartConfig
public class UploadDoc extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/front/DragUploadDoc.jsp").forward(request, response);
    }

    private String getFilename(Part part) {
        String contentDispositionHeader = part.getHeader("content-disposition");
        String[] elements = contentDispositionHeader.split(";");
        for (String element : elements) {
            // System.out.println(element);
            if (element.trim().startsWith("filename")) {
                String fileName = element.substring(element.indexOf('=') + 1).trim().replace("\"", "");
                return new File(fileName).getName();
            }
        }
        return null;
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Map<String, String> inputMap = new HashMap<String, String>();
        Map<String, String> errorMap = new HashMap<String, String>();
        request.setAttribute("input", inputMap);
        request.setAttribute("error", errorMap);
        request.setCharacterEncoding("UTF-8");
        //response.setCharacterEncoding("UTF-8");
        //response.setContentType("text/html; charset=UTF-8");
        boolean success = false;
        User curUser = (User) request.getSession().getAttribute("curUser");
        if (curUser == null) {
            response.sendRedirect("/Login");
        } else {
            Part part = request.getPart("file");
            String fileName = getFilename(part);
            if (fileName == null || fileName.isEmpty()) {
                errorMap.put("file", "没有这个文件");
            }
            if (errorMap.size() == 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String uriPath = "/WEB-INF/file/upload/" + sdf.format(new Date());
                String physicalPath = getServletContext().getRealPath(uriPath);
                if (!new File(physicalPath).exists()) {
                    new File(physicalPath).mkdirs();
                }
                physicalPath += File.separator;
                String fn = UUID.randomUUID().toString();
                physicalPath += fn;
                uriPath += "/" + fn;
                System.out.println(physicalPath);
                // System.out.println(uriPath);
                part.write(physicalPath);
                Doc doc = new Doc();
                doc.setName(fileName);
                doc.setFullName(uriPath);
                doc.setUploadedTime(new Timestamp(new java.util.Date().getTime()));
                doc.setUserId(curUser.getId());
                Dac.getInstance().addDoc(doc);
                JSONObject jsonObject = new JSONObject();
                long docId;
                if ((docId = doc.getId()) > 0) {
                    success = true;
                    // response.sendRedirect("ListDoc");
                    jsonObject.put("docId", docId);
                    jsonObject.put("fileName", fileName);
                    
                } else {
                    //errorMap.put("error", "上传失败");
                    jsonObject.put("docId", 0);
                    jsonObject.put("fileName", "上传失败");
                }
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(jsonObject.toString());
            }
        }
        if (!success)
            request.getRequestDispatcher("/WEB-INF/jsp/front/ListDoc.jsp").forward(request, response);
    }
}
